package com.adinnet.core.interceptor;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 统一日志处理切面
 * Created by yubin
 */
@Aspect
@Component
@Slf4j
public class WebLogAspect {

    @Pointcut("execution(public * com.adinnet.*..controller.*.*(..))")
    public void webLog() {
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String uri = request.getRequestURI();
        //记录入参
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        List<Map> inParameter = getParameter(method, joinPoint.getArgs());
        log.info("---------->> {} begin ! parameter:{}", uri, JSONUtil.parse(inParameter));
        //执行接口
        Object result = joinPoint.proceed();
        //记录出参
        String resultStr = "{}";
        if (ObjectUtils.isNotEmpty(result)) {
            if (result.getClass().equals(String.class)) {
                resultStr = result.toString();
            } else {
                resultStr = JSONUtil.parse(result).toJSONString(0);
                resultStr = resultStr.length() > 3000 ? resultStr.substring(0, 3000) : resultStr;
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("---------->> {} end, time-consuming:{}ms ! result:{}", uri, endTime - startTime, resultStr);
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private List<Map> getParameter(Method method, Object[] args) {
        List<Map> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        for (int i = 0; i < parameters.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put(parameters[i].getName(), args[i]);
            argList.add(map);
        }
        return argList;
    }
}
